package com.xiashitech.agent.instrumentation.base;

import com.xiashitech.agent.instrumentation.base.context.TraceConst;
import com.xiashitech.agent.instrumentation.log.XSLevel;
import io.opentelemetry.javaagent.bootstrap.internal.InstrumentationConfig;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.api.common.AttributesBuilder;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.api.trace.Span;

import java.util.Arrays;
import java.util.logging.Logger;

/**
 * 插桩调试输出工具
 * @author zhaoyk
 */
public class DebugUtils {

    private static final String MARK = "======== XS_DEBUG_INFO ======== ";

    private static boolean isDebugOn() {
        return InstrumentationConfig.get().getBoolean("xs.debug", false);
    }

    public static void print4Debug(String key) {
        print4Debug(key, "");
    }

    public static void print4Debug(String key, Object value) {
        if(isDebugOn()) {
            System.out.println(MARK + key + ":");

            if(!"".equals(value))
                System.out.println("\t" + value);
        }
    }

    public static void setAttribute4Debug(AttributesBuilder attributesBuilder, String key, String val) {
        if(isDebugOn()) {
            attributesBuilder.put(key, val);
        }
    }

    public static void printError4Debug(Throwable e) {
        printError4Debug(e, null);
    }

    public static void printError4Debug(Throwable t, AttributesBuilder attributesBuilder) {
        if(isDebugOn()) {
            print4Debug(t.getMessage());
            t.printStackTrace();

            if(attributesBuilder != null) {
                attributesBuilder.put(TraceConst.XS_EXCEPTION, buildErrorInfo(t));
            } else {
                try {
                    Span.current().setAttribute(TraceConst.XS_EXCEPTION, buildErrorInfo(t));
                } catch (Throwable e) {

                }
            }
        }
    }

    private static String buildErrorInfo(Throwable t) {
        return t.getMessage() + ',' + Arrays.toString(t.getStackTrace());
    }

    public static void log(Logger logger, String info) {
        if(isDebugOn()) {
            logger.log(XSLevel.DEBUG, info);
        }
    }

}
